import React, { useRef, useEffect } from 'react';
import { Canvas, useLoader, useFrame } from '@react-three/fiber';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from '@react-three/drei';
import * as THREE from 'three';

interface GLTF {
  scene: THREE.Group;
  animations: THREE.AnimationClip[];
}

const CharacterAnimation: React.FC = () => {
  // 加载 GLB 文件
  const gltf = useLoader(GLTFLoader, 'your_character.glb') as GLTF;
  const model = gltf.scene;
  const mixer = useRef<THREE.AnimationMixer | null>(null);
  const actions: { [key: string]: THREE.AnimationAction } = {};
  let currentAction: THREE.AnimationAction | null = null;

  useEffect(() => {
    // 创建动画混合器
    mixer.current = new THREE.AnimationMixer(model);

    // 获取所有动画剪辑
    const clips = gltf.animations;

    // 遍历所有动画剪辑并存储到 actions 对象中
    clips.forEach((clip) => {
      const action = mixer.current!.clipAction(clip);
      actions[clip.name] = action;
    });

    // 默认播放第一个动作
    const firstActionName = Object.keys(actions)[0];
    currentAction = actions[firstActionName];
    currentAction.play();
  }, [gltf]);

  // 切换动作的函数
  const switchAction = (actionName: string) => {
    if (actions[actionName]) {
      if (currentAction) {
        currentAction.stop();
      }
      currentAction = actions[actionName];
      currentAction.play();
    }
  };

  // 动画循环
  useFrame((state, delta) => {
    if (mixer.current) {
      mixer.current.update(delta);
    }
  });

  return (
    <Canvas>
      {/* 添加环境光 */}
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} intensity={0.5} />
      {/* 渲染模型 */}
      <primitive object={model} position={[0, -1, 0]} />
      {/* 添加轨道控制器，方便用户交互 */}
      <OrbitControls />
      {/* 动作切换按钮 */}
      <div style={{ position: 'absolute', top: '10px', left: '10px' }}>
        <button onClick={() => switchAction('行走')}>行走</button>
        <button onClick={() => switchAction('奔跑')}>奔跑</button>
        <button onClick={() => switchAction('跳跃')}>跳跃</button>
      </div>
    </Canvas>
  );
};

export default CharacterAnimation;